/**
 * 
 */
package com.scpii.universal.hibernate.dao.impl;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.scpii.universal.constant.GenericConstants;
import com.scpii.universal.hibernate.dao.AppUpdateDao;
import com.scpii.universal.hibernate.entity.AppUpdateTab;

/**
 * genericWeb
 * 
 * @author weny 2012-7-6上午10:44:12
 */
@Repository
public class AppUpdateDaoImpl extends BaseDaoImpl<AppUpdateTab, Integer>
		implements AppUpdateDao {
	@SuppressWarnings("unchecked")
	@Override
	public List<AppUpdateTab> getFirstVersionApp(int appId, String[] properties) {
		String hql = generateHqlByProperties(properties)
				+ "where entity.intDeleteSign=? and entity.varAppDownloadUrl=? and entity.intAppId=?";
		return (List<AppUpdateTab>) getHibernateTemplate().getSessionFactory()
				.getCurrentSession().createQuery(hql).setParameter(0,
						GenericConstants.DELETE_SIGN_EXIST).setParameter(1,
						null).setParameter(2, appId).list();
	}

	@Override
	public AppUpdateTab getVersionUpdateInfo(int appId,
			String[] properties, int type) {
		
		StringBuffer hql = new StringBuffer(generateHqlByProperties(properties));
		hql.append("where entity.intDeleteSign=? and ");
		hql.append("entity.dobAppVersion=(select max(a.dobAppVersion) ");
		hql.append("from AppUpdateTab a where a.intDeleteSign=? and a.intAppOsType=? and a.intAppId=?)");
		hql.append(" and entity.intAppOsType=? and entity.intAppId=?");
		return (AppUpdateTab) getHibernateTemplate().getSessionFactory()
				.getCurrentSession().createQuery(hql.toString()).setParameter(0,
						GenericConstants.DELETE_SIGN_EXIST).setParameter(1,
						GenericConstants.DELETE_SIGN_EXIST).setParameter(2,
						type).setParameter(3, appId).setParameter(4, type)
				.setParameter(5, appId).uniqueResult();
	}

	@SuppressWarnings("unchecked")
	@Override
	public AppUpdateTab getMaxVersion(int appId,String[] properties, int type) {
		String hql = generateHqlByProperties(properties)
				+ "where entity.intDeleteSign=? and"
				+ " entity.intAppOsType=? and entity.intAppId=?"
				+ " and entity.varAppDownloadUrl is not null"
				+ " order by entity.dobAppVersion desc";
		List<AppUpdateTab> resutls = getHibernateTemplate().getSessionFactory()
				.getCurrentSession().createQuery(hql)
				.setParameter(0, GenericConstants.DELETE_SIGN_EXIST)
				.setParameter(1, type).setParameter(2, appId).list();
		if(resutls != null && resutls.size() > 0)
			return resutls.get(0);
		return null;
	}

}
